<template>
  <div class="satisfaction-survey-detail">
    <!-- 页面头部 -->
    <el-page-header @back="$router.go(-1)" title="满意度调查详情" />

    <!-- 季度统计概览 -->
    <div class="statistics-overview">
      <el-card>
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="stat-item">
              <div class="stat-number total">{{ statistics.total }}</div>
              <div class="stat-label">季度目标</div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="stat-item">
              <div class="stat-number completed">{{ statistics.completed }}</div>
              <div class="stat-label">已调研</div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="stat-item">
              <div class="stat-number pending">{{ statistics.pending }}</div>
              <div class="stat-label">待调研</div>
            </div>
          </el-col>
        </el-row>

        <!-- 进度条 -->
        <div class="progress-section">
          <div class="progress-info">
            <span>本季度完成进度</span>
            <span>{{ completionRate }}%</span>
          </div>
          <el-progress :percentage="completionRate" :color="progressColor" />
        </div>

        <!-- 截止时间提醒 -->
        <div class="deadline-reminder">
          <el-alert
            :title="deadlineText"
            type="warning"
            :closable="false"
            show-icon
          />
        </div>
      </el-card>
    </div>

    <!-- 时段选择 -->
    <div class="month-selector">
      <el-card>
        <el-button @click="showMonthPicker = true" type="text">
          <el-icon><Calendar /></el-icon>
          选择时段: {{ selectedMonth }}
        </el-button>
      </el-card>
    </div>

    <!-- 搜索和筛选 -->
    <div class="search-filter">
      <el-card>
        <el-input
          v-model="searchKeyword"
          placeholder="搜索客户代码或客户名称"
          clearable
          @input="handleSearch"
          @clear="handleClear"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>

        <div class="filter-tabs">
          <el-tabs v-model="activeTab" @tab-change="handleTabChange">
            <el-tab-pane label="全部" name="all" />
            <el-tab-pane label="已完成" name="completed" />
            <el-tab-pane label="未完成" name="pending" />
          </el-tabs>
        </div>
      </el-card>
    </div>

    <!-- 客户列表 -->
    <div class="client-list">
      <el-card>
        <div v-loading="loading">
          <div v-for="client in filteredClients" :key="client.id" class="client-item">
            <el-card class="client-card" shadow="hover" @click="viewClientDetail(client)">
              <div class="client-header">
                <div class="client-title">
                  <h4>{{ client.clientName }}</h4>
                  <el-tag
                    :type="client.status === 'completed' ? 'success' : 'warning'"
                    size="small"
                  >
                    {{ client.status === 'completed' ? '已完成' : '未完成' }}
                  </el-tag>
                </div>
                <div class="client-meta">
                  <span class="client-code">{{ client.clientCode }}</span>
                  <span class="client-type">{{ client.marketType }} | {{ client.terminalType }}</span>
                </div>
              </div>

              <div class="client-content">
                <div class="satisfaction-info">
                  <div v-if="client.status === 'completed'" class="satisfaction-score">
                    <span>满意度评分：</span>
                    <el-rate
                      :model-value="parseFloat(client.satisfactionScore)"
                      disabled
                      show-score
                      text-color="#ff9900"
                      size="small"
                    />
                  </div>
                  <div class="completion-time">
                    <el-icon><Clock /></el-icon>
                    {{ client.completedTime || '未完成' }}
                  </div>
                </div>
              </div>

              <div class="client-actions" @click.stop>
                <el-button
                  v-if="client.status === 'pending'"
                  type="primary"
                  size="small"
                  @click="startSurvey(client)"
                >
                  开始调查
                </el-button>
                <el-button
                  v-else
                  type="default"
                  size="small"
                  @click="viewSurveyResult(client)"
                >
                  查看结果
                </el-button>
                <el-button
                  v-if="client.status === 'completed'"
                  type="danger"
                  size="small"
                  @click="deleteSurveyRecord(client)"
                >
                  删除
                </el-button>
              </div>
            </el-card>
          </div>

          <div v-if="!finished && filteredClients.length > 0" class="load-more">
            <el-button @click="onLoad" :loading="loading">加载更多</el-button>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 客户详情弹窗 -->
    <el-dialog v-model="showClientDetail" title="客户详情" width="90%">
      <div v-if="selectedClient">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="客户代码">{{ selectedClient.clientCode }}</el-descriptions-item>
          <el-descriptions-item label="客户名称">{{ selectedClient.clientName }}</el-descriptions-item>
          <el-descriptions-item label="市场类型">{{ selectedClient.marketType }}</el-descriptions-item>
          <el-descriptions-item label="终端类型">{{ selectedClient.terminalType }}</el-descriptions-item>
          <el-descriptions-item label="调查状态">
            <el-tag :type="selectedClient.status === 'completed' ? 'success' : 'warning'">
              {{ selectedClient.status === 'completed' ? '已完成' : '未完成' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item
            v-if="selectedClient.status === 'completed'"
            label="完成时间"
          >
            {{ selectedClient.completedTime }}
          </el-descriptions-item>
          <el-descriptions-item
            v-if="selectedClient.status === 'completed'"
            label="满意度评分"
          >
            <el-rate
              :model-value="parseFloat(selectedClient.satisfactionScore)"
              disabled
              show-score
              text-color="#ff9900"
            />
          </el-descriptions-item>
          <el-descriptions-item
            v-if="selectedClient.notes"
            label="调查备注"
          >
            {{ selectedClient.notes }}
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showClientDetail = false">关闭</el-button>
          <el-button
            v-if="selectedClient?.status === 'pending'"
            type="primary"
            @click="startSurvey(selectedClient)"
          >
            开始满意度调查
          </el-button>
          <el-button
            v-else-if="selectedClient?.status === 'completed'"
            type="default"
            @click="viewSurveyResult(selectedClient)"
          >
            查看调查结果
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 浮动操作按钮 -->
    <div class="fab-container">
      <el-button
        type="primary"
        circle
        @click="createNewSurvey"
      >
        <el-icon><Plus /></el-icon>
      </el-button>
    </div>

    <!-- 时段选择器 -->
    <el-dialog v-model="showMonthPicker" title="选择时段" width="300px">
      <div class="period-selector">
        <p style="margin-bottom: 16px; color: #606266;">满意度调研按季度进行统计</p>
        <el-radio-group v-model="selectedPeriod" @change="confirmPeriod">
          <el-radio value="quarter">当前季度</el-radio>
        </el-radio-group>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showMonthPicker = false">取消</el-button>
          <el-button type="primary" @click="confirmPeriod">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, SuccessFilled, Clock, Plus, Calendar } from '@element-plus/icons-vue'
import { trpc } from '@/utils/trpc'
import { AuthUtils } from '@/utils/auth'

const router = useRouter()

// 响应式数据
const searchKeyword = ref('')
const activeTab = ref('all')
const loading = ref(false)
const finished = ref(false)
const showClientDetail = ref(false)
const showMonthPicker = ref(false)
const selectedClient = ref(null)

// 初始化为当前季度
const now = new Date()
const currentQuarter = Math.ceil((now.getMonth() + 1) / 3)
const selectedMonth = ref(`${now.getFullYear()}年第${currentQuarter}季度`)
const selectedPeriod = ref('quarter')

// 统计数据
const statistics = reactive({
  total: 0,
  completed: 0,
  pending: 0
})

// 客户列表数据和服务信息
const clients = ref([])
const satisfactionService = ref(null)

// 计算属性
const completionRate = computed(() => {
  return Math.round((statistics.completed / statistics.total) * 100)
})

const progressColor = computed(() => {
  const rate = completionRate.value
  if (rate >= 80) return '#07c160'
  if (rate >= 60) return '#ff976a'
  return '#ff6b6b'
})

const filteredClients = computed(() => {
  let filtered = clients.value

  // 根据搜索关键词过滤
  if (searchKeyword.value) {
    filtered = filtered.filter(client => 
      client.clientCode.includes(searchKeyword.value) ||
      client.clientName.includes(searchKeyword.value)
    )
  }

  // 根据状态标签过滤
  if (activeTab.value !== 'all') {
    const statusMap = {
      'completed': 'completed',
      'pending': 'pending'
    }
    filtered = filtered.filter(client => client.status === statusMap[activeTab.value])
  }

  return filtered
})

// 方法
const handleSearch = () => {
  // 搜索逻辑已在计算属性中处理
}

const handleClear = () => {
  searchKeyword.value = ''
}

const handleTabChange = (name) => {
  activeTab.value = name
}

const onLoad = async () => {
  try {
    loading.value = true
    // 模拟加载更多数据
    await new Promise(resolve => setTimeout(resolve, 1000))
    // 这里可以加载更多数据
    finished.value = true
  } catch (error) {
    ElMessage.error('加载失败')
  } finally {
    loading.value = false
  }
}

const viewClientDetail = (client) => {
  selectedClient.value = client
  showClientDetail.value = true
}

const startSurvey = (client) => {
  showClientDetail.value = false
  // 跳转到满意度调研主页面，并传递参数以自动打开添加对话框
  router.push({
    name: 'SatisfactionSurvey',
    query: { action: 'add', clientId: client.id }
  })
}

const viewSurveyResult = (client) => {
  ElMessage.success(`查看 ${client.clientName} 的调查结果`)
  showClientDetail.value = false
}

const createNewSurvey = () => {
  // 跳转到满意度调研主页面，并传递参数以自动打开添加对话框
  router.push({
    name: 'SatisfactionSurvey',
    query: { action: 'add' }
  })
}

const deleteSurveyRecord = async (client) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除客户"${client.clientName}"的满意度调研记录吗？删除后无法恢复。`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const managerId = getCurrentManagerId()
    if (!managerId) return

    if (!client.workLogId) {
      ElMessage.error('未找到对应的调研记录')
      return
    }

    // 调用API删除记录
    const result = await trpc.workLog.delete.mutate({
      id: client.workLogId.toString(),
      managerId
    })

    if (result.success) {
      // 更新本地数据
      const clientIndex = clients.value.findIndex(c => c.id === client.id)
      if (clientIndex > -1) {
        // 将状态改为未完成
        clients.value[clientIndex].status = 'pending'
        clients.value[clientIndex].completedTime = null
        clients.value[clientIndex].satisfactionScore = null
        clients.value[clientIndex].notes = null
        clients.value[clientIndex].workLogId = null
      }
      
      // 更新统计数据
      statistics.completed--
      statistics.pending++
      
      ElMessage.success('删除成功')
    } else {
      ElMessage.error('删除失败')
    }
  } catch (error) {
    console.error('删除满意度调研记录失败:', error)
    if (error.message !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const deadlineText = computed(() => {
  const remaining = statistics.pending
  if (remaining === 0) {
    return '本季度满意度调研已全部完成！'
  }
  return `本季度还需完成 ${remaining} 次满意度调研，请及时完成`
})

const confirmPeriod = () => {
  showMonthPicker.value = false
  loadData() // 重新加载该季度的数据
}

const getCurrentQuarterRange = () => {
  const now = new Date()
  const quarter = Math.ceil((now.getMonth() + 1) / 3)
  const startMonth = (quarter - 1) * 3
  const startDate = new Date(now.getFullYear(), startMonth, 1)
  const endDate = new Date(now.getFullYear(), startMonth + 3, 0)
  return { startDate, endDate }
}

const getCurrentManagerId = () => {
  const user = AuthUtils.getUser()
  return user?.id || null
}

const loadData = async () => {
  try {
    loading.value = true
    const managerId = getCurrentManagerId()
    if (!managerId) return

    // 获取满意度调研服务
    const serviceList = await trpc.service.list.query({ pageSize: 100 })
    if (!serviceList?.success) throw new Error('加载服务列表失败')
    const services = serviceList.data.data || serviceList.data || []
    const foundService = services.find((s) => s.serviceName?.includes('满意度'))
    
    if (!foundService) {
      console.warn('未找到满意度调研服务')
      return
    }
    
    satisfactionService.value = foundService
    
    // 获取该经理负责的客户列表
    const clientList = await trpc.manager.clients.query({ 
      managerId, 
      pageSize: 100 // 最大页面大小
    })
    if (!clientList?.success) throw new Error('加载客户列表失败')
    
    const allClients = clientList.data.data || []
    
    // 计算本季度时间范围（与主页面保持一致）
    const { startDate, endDate } = getCurrentQuarterRange()
    
    // 获取该季度的满意度调研工作记录（与主页面保持一致）
    const workLogResult = await trpc.workLog.serviceStats.query({
      managerId,
      serviceId: foundService.id,
      startDate: startDate.toISOString(),
      endDate: endDate.toISOString()
    })

    if (workLogResult.success) {
      // 使用与主页面相同的数据结构
      const statsData = workLogResult.data
      const recentLogs = statsData.recentLogs || []
      
      // 更新统计数据（与主页面保持一致）
      statistics.total = statsData.totalClients || 0
      statistics.completed = statsData.completedCount || 0
      statistics.pending = statsData.uncompletedCount || 0
      
      // 获取已完成满意度调研的客户ID
      const completedClientIds = new Set(recentLogs.map(log => log.clientId))
      
      // 筛选出被分配了满意度调研服务的客户，并构建显示数据
      const satisfactionClients = allClients.filter(client => {
        return client.serviceAssignments && client.serviceAssignments.some(assignment => 
          assignment.service.id === foundService.id
        )
      })
      
      clients.value = satisfactionClients.map(client => {
        const isCompleted = completedClientIds.has(client.id)
        const workLog = recentLogs.find(log => log.clientId === client.id)
        
        return {
          id: client.id,
          clientCode: client.clientCode,
          clientName: client.clientName,
          marketType: client.marketType,
          terminalType: client.terminalType,
          status: isCompleted ? 'completed' : 'pending',
          completedTime: isCompleted ? new Date(workLog.completionDate).toLocaleString() : null,
          satisfactionScore: isCompleted ? (Math.random() * 2 + 3).toFixed(1) : null, // 模拟评分3-5分
          notes: workLog?.notes || null,
          workLogId: workLog?.id || null // 保存工作日志ID以便删除时使用
        }
      })
    }
  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

// 生命周期
onMounted(() => {
  loadData()
})
</script>

<style scoped>
.satisfaction-survey-detail {
  background-color: #f5f5f5;
  min-height: 100vh;
  padding: 20px;
  padding-bottom: 80px;
}

.statistics-overview {
  margin-bottom: 20px;
}

.deadline-reminder {
  margin-top: 20px;
  padding: 0 20px;
}

.month-selector {
  margin-bottom: 20px;
}

.stat-item {
  text-align: center;
  padding: 20px;
}

.stat-number {
  font-size: 28px;
  font-weight: bold;
  margin-bottom: 8px;
}

.stat-number.total {
  color: #333;
}

.stat-number.completed {
  color: #67c23a;
}

.stat-number.pending {
  color: #e6a23c;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

.progress-section {
  margin-top: 30px;
  padding: 0 20px;
}

.progress-info {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  font-size: 14px;
  font-weight: bold;
}

.search-filter {
  margin-bottom: 20px;
}

.filter-tabs {
  margin-top: 15px;
}

.client-list {
  margin-bottom: 20px;
}

.client-item {
  margin-bottom: 15px;
}

.client-card {
  cursor: pointer;
  transition: all 0.3s;
}

.client-card:hover {
  transform: translateY(-2px);
}

.client-header {
  margin-bottom: 15px;
}

.client-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.client-title h4 {
  margin: 0;
  font-size: 16px;
  font-weight: bold;
}

.client-meta {
  display: flex;
  gap: 15px;
  font-size: 14px;
  color: #666;
}

.client-code {
  font-weight: bold;
  color: #333;
}

.client-type {
  color: #409eff;
}

.client-content {
  margin-bottom: 15px;
}

.satisfaction-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.satisfaction-score {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
}

.completion-time {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  color: #999;
}

.client-actions {
  display: flex;
  gap: 8px;
  justify-content: flex-end;
}

.load-more {
  text-align: center;
  margin-top: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.fab-container {
  position: fixed;
  bottom: 30px;
  right: 30px;
  z-index: 999;
}

.fab-container .el-button {
  width: 56px;
  height: 56px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.el-rate {
  --el-rate-icon-size: 16px;
}

.satisfaction-score .el-rate {
  --el-rate-icon-size: 14px;
}

.period-selector {
  padding: 16px 0;
}

.period-selector .el-radio-group {
  width: 100%;
}

.period-selector .el-radio {
  width: 100%;
  margin: 8px 0;
}
</style>
